package com.examples.gateway.helper.filter;

import com.examples.gateway.common.CheckState;
import com.examples.gateway.helper.utils.CheckStateHelpUtils;
import com.examples.gateway.helper.Constants;
import com.examples.gateway.helper.entity.ResponseContext;
import com.examples.gateway.provider.ResponseProvider;
import com.alibaba.nacos.common.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Collections;

@Slf4j
public abstract class AbstractGlobalHelperFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (skipHelperFilter(exchange)) {
            return chain.filter(exchange);
        } else {
            return doFilter(exchange, chain);
        }
    }

    public abstract Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain);

    private boolean skipHelperFilter(ServerWebExchange exchange) {
        CheckState state = (CheckState)exchange.getAttributes().get(Constants.EXAMPLES_GATEWAY_CHECK_STATE);
        return state != null && CheckStateHelpUtils.isSkipLeft(state);
    }

    private void setHeaders(ServerHttpResponse response) {
        HttpHeaders headers = response.getHeaders();
        headers.put(HttpHeaders.ACCEPT_CHARSET, Collections.singletonList("utf-8"));
        headers.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList("application/json"));
    }

    protected Mono<Void> handleError(ServerHttpResponse response, ResponseContext resCtx) {
        setHeaders(response);
        response.setStatusCode(resCtx.getHttpStatus());
        Object ret = ResponseProvider.response(resCtx.getHttpStatus().value(), resCtx.getCheckState().getCode());
        String jsonRet = JacksonUtils.toJson(ret);
        log.warn("gateway error message: {}", jsonRet);
        DataBufferFactory factory = response.bufferFactory();
        DataBuffer dataBuffer = factory.wrap(jsonRet.getBytes(StandardCharsets.UTF_8));
        return response.writeAndFlushWith(Flux.just(dataBuffer).map(Flux::just));
    }

    protected Mono<Void> handleError(ServerWebExchange exchange, ResponseContext resCtx) {
        return handleError(exchange.getResponse(), resCtx);
    }

    protected Mono<Void> handleError(ServerWebExchange exchange, CheckState state) {
        ResponseContext resCtx = new ResponseContext();
        resCtx.setCheckState(state);
        return handleError(exchange, resCtx);
    }

}
